package com.edu.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.edu.order.bean.Order;
import com.edu.order.feign.ProductFeignClient;
import com.edu.order.service.OrderService;
import com.edu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;

    // 编程式REST客户端
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //    @Qualifier("productFeignClient")
    @Autowired
    private ProductFeignClient productFeignClient;

    // 未指定异常处理机制，会使用默认的全局异常处理机制
    //
    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Order order) {
//        Product product = getProductFromRemoteById(1L);
        Product product = productFeignClient.getProductById(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        ArrayList<Product> list = new ArrayList<>();
        list.add(product);
        order.setProductList(list);
        return order;
    }

    @Override
    public Product getProductFromRemoteById(Long id) {
        // 1. 获取商品服务所在的所有机器IP + port
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        // 负载均衡写法
        ServiceInstance instance = loadBalancerClient.choose("service-product");
//        ServiceInstance instance;
        if (instance != null) {
            String url = instance.getUri() + "/product/" + id;
            log.info("url: {}", url);
            // 2. 给远程发送请求
            return restTemplate.getForObject(url, Product.class);
        }
        return null;
    }

    @Override
    public Product getProductFromRemoteByIdWithLoadBalanceAnnotation(Long id) {
        return restTemplate.getForObject(
                "http://service-product/product/" + id,
                Product.class);
    }

    public Order createOrderFallback(Order order, BlockException exception) {
        order.setAddress("没有指定商品:" + exception.getMessage());
        return order;
    }

}
